<route lang="json">
{
  "meta": {
    "title": "t('jie-chu-liu-dong-xing')"
  }
}
</route>
<script lang="ts" setup name="swap-removeLiquidity">
import useBalanceStore from "@@/store/useBalanceStore";
import { _require } from "@@/utils/tools";
import {
  fixedDecimals,
  foldDecimal,
  omitText,
  normalNumber,
} from "@@/utils/tools/format";
import { useWkLpInfo, LpCoin } from "@@/views-tabbar/swap/wkLoopInfo";
import { divide, multiply } from "mathjs";
import { sdkRemoveLiquidity } from "@@/sdk/web3Eth";
import { toast, notify } from "@@/hooks/vantHooks";
import { copyText } from "@@/utils/tools/project";
import { parseBalance } from "@@/sdk/index";
import { addCache } from "@@/hooks/routeCache";
import useTabPageStore from "@@/store/useTabPageStore";

addCache("swap-removeLiquidity");
const balanceStore = useBalanceStore();
const tabPageStore = useTabPageStore();

const contract_addr = computed(() => tabPageStore.homeData?.wkc.contract_addr);
const { lpCoinEnum, lpInfo } = useWkLpInfo([contract_addr.value!]);

const coin0 = computed(() => balanceStore.getCoinByCode("USDT"));
const coin1 = computed(() => balanceStore.getCoinByCode("WKC"));

const lpCoin0 = computed<LpCoin | undefined>(
  () => lpCoinEnum.value[coin0.value?.id!]
);
const lpCoin1 = computed<LpCoin | undefined>(
  () => lpCoinEnum.value[coin1.value?.id!]
);

/**要移除的数量 */
const remove0Amount = computed(() => {
  return divide(multiply(Number(lpCoin0.value?.balance), formData.rate), 100);
});
/**要移除的数量 */
const remove1Amount = computed(() => {
  return divide(multiply(Number(lpCoin1.value?.balance), formData.rate), 100);
});
/**要移除的数量! 未处理精度 */
const removeAmount__ = computed(() =>
  divide(multiply(Number(lpInfo.value?.balance__), formData.rate), 100)
);

const formData = reactive({
  rate: 0,
});
const btnLoading = reactive({
  submitBtn: false,
  approveToBtn: false,
  approveFromBtn: false,
  approveBtn: false,
});
const { t } = useI18n();
async function submitBtn() {
  if (!lpCoin0.value?.format)
    return toast.error(t("shu-ju-yi-chang-qing-chong-shi"));
  btnLoading.submitBtn = true;
  const value = normalNumber(Math.ceil(removeAmount__.value));
  const res = await sdkRemoveLiquidity(
    [lpCoin0.value?.contract_addr!, lpCoin1.value?.contract_addr!],
    value,
    balanceStore.approveAddresss
  );
  btnLoading.submitBtn = false;
  if (!res.status) return notify.error(res.message || "fail");
  notify.success(`${t("jie-chu-cheng-gong")} ${omitText(res.data)}`, {
    onClick() {
      copyText(res.data!);
    },
  });
}
/**lp币种 */
const lpTokenInfo = computed<any>(() => ({
  contract_addr: tabPageStore.homeData?.address.pair_address!,
  format: lpCoin1.value?.format || 18,
  code: "",
}));

/**lp币种批准状态 */
const lpCoinApprove = computed(
  () =>
    approveAmount.value >=
    Number(parseBalance(removeAmount__.value, lpCoin1.value?.format || 18))
);

const approveAmount = ref(0);
async function approveBtn() {
  btnLoading.approveBtn = true;
  await balanceStore.approve(
    lpTokenInfo.value,
    undefined,
    balanceStore.approveAddresss
  );
  btnLoading.approveBtn = false;
  checkApprove();
}
async function checkApprove() {
  const res = await balanceStore.findApprove(
    lpTokenInfo.value,
    balanceStore.approveAddresss
  );
  return (approveAmount.value = Number(res) || 0);
}
onActivated(checkApprove);
checkApprove();
</script>
<template>
  <CpageView>
    <Ccard class="auto-MT-md T-S-sm">
      <div class="flex-A-C">
        <Rimage size="42rem" :src="lpCoin0?.logo" />
        <Rimage size="42rem" :src="lpCoin1?.logo" />
        <div class="ML-xs">{{ lpCoin0?.code }}/{{ lpCoin1?.code }}</div>
        <div class="C-M1 B-M1-O1 ML-auto R-max PD-xs">
          {{ foldDecimal(Number(lpInfo?.myRatio) * 100, 6) }}%
        </div>
      </div>
      <Ccard bg="var(--C-B3)" class="PT-xs PB-xs">
        <Ccell border-mode="bottom">
          <div class="C-T3">{{ lpCoin0?.code }}{{ $t("shu-liang") }}</div>
          <template #right>
            <div>{{ foldDecimal(lpCoin0?.balance, 4) }}</div>
          </template>
        </Ccell>
        <Ccell border-mode="bottom">
          <div class="C-T3">{{ lpCoin1?.code }}{{ $t("shu-liang") }}</div>
          <template #right>
            <div>{{ foldDecimal(lpCoin1?.balance, 4) }}</div>
          </template>
        </Ccell>
      </Ccard>
      <h3 class="MT-lg">{{ $t("jie-chu-shu-liang") }}</h3>
      <Ccard bg="var(--C-B3)" class="PT-xs PB-xs">
        <Ccell border-mode="bottom">
          <div class="C-T3">{{ lpCoin0?.code }}{{ $t("shu-liang") }}</div>
          <template #right>
            <div>{{ foldDecimal(remove0Amount, 4) }}</div>
          </template>
        </Ccell>
        <Ccell border-mode="bottom">
          <div class="C-T3">{{ lpCoin1?.code }}{{ $t("shu-liang") }}</div>
          <template #right>
            <div>{{ foldDecimal(remove1Amount, 4) }}</div>
          </template>
        </Ccell>
      </Ccard>

      <div class="PD-md">
        <Rslider v-model="formData.rate" max="100" min="0" step="0.1">
          <template #button>
            <CstateTag class="T-nowrap C-white">
              {{ formData.rate }}%
            </CstateTag>
          </template>
        </Rslider>
      </div>
    </Ccard>
    <TransitionGroup name="page">
      <Rbutton
        class="MT-md"
        @click="approveBtn"
        key="1"
        :loading="btnLoading.approveBtn"
        v-if="!lpCoinApprove"
        :size="'large'"
        bg="var(--C-LG1)" borderStyle="none"
      >
        {{ $t("pi-zhun") }}
      </Rbutton>
      <Rbutton
        class="MT-md"
        v-if="lpCoinApprove"
        @click="submitBtn"
        key="2"
        :loading="btnLoading.submitBtn"
        :disabled="!(removeAmount__ > 0)"
        :size="'large'"
        bg="var(--C-LG1)" borderStyle="none"
      >
        {{ $t("jie-chu") }}
      </Rbutton>
    </TransitionGroup>
  </CpageView>
</template>
<style lang="scss" scoped>
.imgBgCard {
  background-position: 50% 50%;
  background-size: cover;
  background-repeat: no-repeat;
}
.subBtn-wrap {
  margin: var(--gap-xxl);
}
</style>
